package com.ie.cloud.payment.service.impl;

import cn.hutool.http.ContentType;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.icbc.api.IcbcApiException;
import com.icbc.api.utils.IcbcEncrypt;
import com.icbc.api.utils.IcbcSignature;
import com.ie.cloud.payment.constants.BizStatus;
import com.ie.cloud.payment.entity.MchApp;
import com.ie.cloud.payment.exception.BizException;
import com.ie.cloud.payment.mapper.MchAppMapper;
import com.ie.cloud.payment.service.impl.event.CallbackMessagePublishService;
import com.ie.cloud.payment.service.impl.event.PushPayInfoMsgEventPublishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * Created with FR
 *
 * @Author: DQ
 * @Date: 2025/07/17/19:30
 * @Description: 描述语句
 */
@Service
@Slf4j
public class NoticeService {


    private static final String apigwPubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCMpjaWjngB4E3ATh+G1DVAmQnIpiPEFAEDqRfNGAVvvH35yDetqewKi0l7OEceTMN1C6NPym3zStvSoQayjYV+eIcZERkx31KhtFu9clZKgRTyPjdKMIth/wBtPKjL/5+PYalLdomM4ONthrPgnkN4x4R0+D4+EBpXo8gNiAFsNwIDAQAB";

    private static final String privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDOMNnDxb9iUXQhwSoM/K5oQrFxKDvaz5cqASM1RkYF11Wh5qe0MDPAl+g6ITDYVdYJEH1kWqL4C3YTQIWO7/9QA/g3cVw2kIQsLZvaVk0qgsFAkc0XKVcYdTVmUZYo2hwBDbcjqn+As9P6x+6vv+h8kdq0h7f/kDahVT1T27LGEnfGgdGP8yLb6dOCGeN1/AIT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ESgYw7UHA4O9z1OPaE+07WHT5GTTQffAlAZ8GKt5QKJwOCHygEr6b9AOMqL11Wydy5F4gaNsdxs6s9AXBUoymOipM1UxbRXyY0Mbxepdr2y0wq60oSsLVTAevDnCifI/AoGANQBQocY8l2t+ilr2Ds/NSRvcenIIXwKPLB8hAJVUdObXCM+aBI+oYw6DqVpJ0g2Bcnh5lEwKtGPB5EqlpBVy6cTajzP/qJHfIxB+W1aR4dlgcnjHEro2bj8Jb1GDueIvfagIYkW09UT5WPvjEDZEHnjfzWCELjrIr1WKDDjG3pI=";


    public static final String path = "/ie-payment/api/callback/call";

    @Resource
    private MchAppMapper mchAppMapper;

    @Resource
    private CallbackMessagePublishService callbackMessagePublishService;

    @Resource
    private PushPayInfoMsgEventPublishService pushPayInfoMsgEventPublishService;


    /**
     * 身份校验
     *
     * @param request
     * @param response
     * @param checkFlag 1
     */
    public void identityCheck(HttpServletRequest request, HttpServletResponse response, String checkFlag) {
        log.info("----------接收到推送,开始身份校验----------");


        response.setContentType(ContentType.JSON.toString(StandardCharsets.UTF_8));
        response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        response.setStatus(HttpServletResponse.SC_OK);


        String icbcSign;
        String from;
        String checkStr;
        String signstr;

        //如果是校验请求,校验身份
        icbcSign = request.getHeader("Icbc-Sign");
        from = request.getParameter("from");
        checkStr = request.getParameter("check_str");
        signstr = "check_flag=1&check_str=" + checkStr + "&from=" + from;


        try {
            //先验签
            log.info("signstr {}",signstr);
            log.info("apigwPubKey {}" ,apigwPubKey);
            log.info("icbcSign {}" ,icbcSign);
            boolean passed = IcbcSignature.verify(signstr,
                    "RSA",
                    apigwPubKey,//公钥
                    StandardCharsets.UTF_8.toString(),
                    icbcSign);
            if (passed) {
                log.info("privateKey {}" ,privateKey);
                //验签通过进行签名
                String sign = "";
                sign = IcbcSignature.sign(
                        signstr,
                        "RSA2",
                        privateKey,
                        StandardCharsets.UTF_8.toString());
                log.info("签名信息 {}", sign);
                log.info("身份验证通过");
                response.setHeader("Check-Sign", sign);

            } else {
                log.error("ICBC identity sign verify failed!");
            }

        } catch (IcbcApiException e) {
            log.error("验签失败", e);
            throw new BizException(BizStatus.VALIDATION_FAILED);
        }
    }


    /**
     * 消息推送
     *
     * @param request
     * @param response
     * @param checkFlag 0
     */
    public void messagePush(HttpServletRequest request, HttpServletResponse response, String checkFlag) {
        //正式推送消息请求
        log.info("----------接收到推送,正式推送消息请求----------");


        response.setContentType(ContentType.JSON.toString(StandardCharsets.UTF_8));
        response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        response.setStatus(HttpServletResponse.SC_OK);
        PrintWriter out = null;
        JSONObject returnMap = new JSONObject(true);







        try {//先验签

            String icbcSign = "";
            String from = "";
            String api = "";
            String appId = "";
            String charset = "";
            String format;
            String encryptType = "";
            String timestamp = "";
            String bizContent = "";
            String signType = "";
            String msgId = "";
            String CheckFlag = "";

            log.info("开始========1");



            icbcSign = request.getHeader("Icbc-Sign");

            log.info("icbcSign {}",icbcSign);

            from = request.getParameter("from");

            log.info("from {}",from);

            api = request.getParameter("api");

            log.info("api {}",api);

            appId = request.getParameter("app_id");

            log.info("appId {}",appId);

            charset = request.getParameter("charset");

            log.info("charset {}",charset);

            format = request.getParameter("format");

            log.info("format {}",format);

            encryptType = request.getParameter("encrypt_type");

            log.info("encryptType {}",encryptType);

            timestamp = request.getParameter("timestamp");

            log.info("timestamp {}",timestamp);

            bizContent = request.getParameter("biz_content");

            log.info("bizContent {}",bizContent);

            signType = request.getParameter("sign_type");

            log.info("signType {}",signType);

            msgId = request.getParameter("msg_id");

            log.info("msgId {}",msgId);

            CheckFlag = request.getParameter("check_flag");

            log.info("check_flag {}",CheckFlag);




            StringBuilder s = new StringBuilder();
            s.append(path);

            log.info("s {}", s.toString());
            s.append("?");
            s.append("api=");
            s.append(api);
            s.append("&");
            s.append("app_id=");
            s.append(appId);
            s.append("&");
            s.append("biz_content=");
            s.append(bizContent);
            s.append("&");
            s.append("charset=");
            s.append(charset);
            s.append("&");
            s.append("check_flag=");
            s.append(CheckFlag);
            s.append("&");
            if ("AES".equals(encryptType)) {
                s.append("encrypt_type=");
                s.append(encryptType);
                s.append("&");
            }
            s.append("format=");
            s.append(format);
            s.append("&");
            s.append("from=");
            s.append(from);
            s.append("&");
            s.append("msg_id=");
            s.append(msgId);
            s.append("&");
            s.append("sign_type=");
            s.append(signType);
            s.append("&");
            s.append("timestamp=");
            s.append(timestamp);
            String signStr = s.toString();
            log.info("signStr is: {}", signStr);

            MchApp mchApp = mchAppMapper.selectOne(new LambdaQueryWrapper<MchApp>().eq(MchApp::getAppId, appId));
            if (mchApp == null) {
                log.error("商户不存在");
                throw new BizException(BizStatus.VALIDATION_FAILED);
            }

            boolean passed = IcbcSignature.verify(signStr, "RSA", mchApp.getAppPublicKey(), "UTF-8", icbcSign);

            if (passed) {
                //操作
                String returnBizContent = "{" +
                        "\"msg_id\":\"" +
                        msgId +
                        "\"," +
                        "\"return_code\":0,\"return_msg\":\"success.\"" +
                        "}";
                if ("AES".equals(encryptType)) {
                    returnBizContent = IcbcEncrypt.encryptContent(returnBizContent, "AES", "soxyd6CbYJ9824pQrg0zvw==", "utf-8");
                }
                log.info("responseStr is: {}", returnBizContent);

                returnMap.put("response_biz_content", returnBizContent);
                returnMap.put("sign_type", "RSA");
                returnMap.put("biz_content", bizContent);
                String returnStr = returnMap.toString();





                log.info("returnStr  {}",returnStr);


                JSONObject msgJson = JSONObject.parseObject(bizContent);

                msgJson.put("appId", appId);
                callbackMessagePublishService.publish(msgJson.toString());
                pushPayInfoMsgEventPublishService.publish(msgJson.toString());
//                String sign = IcbcSignature.sign(returnStr, "RSA2", mchApp.getAppSecret(), "UTF-8");
//                response.setContentType("application/json;charset=utf-8");
//                response.setHeader("Resp-Sign", sign);
//                out.print(returnStr);

//                callbackMessagePublishService.publish(returnStr);
            } else {
                log.error("ICBC message sign verify failed!");
            }

        } catch (Exception e) {
            log.error("消息推送调用失败 {}",e.getMessage());
            throw new BizException(BizStatus.VALIDATION_FAILED);

        }
    }




    public void verifySign(HttpServletRequest request, HttpServletResponse response) {
        String checkFlag = request.getParameter("check_flag");


        log.info("----------接收到推送----------");

        log.info("当前请求校验标志位 {}, {}",checkFlag, "1".equals(checkFlag) ? "校验身份" : "正式推送消息");

        if (checkFlag == null) {
            throw new BizException(BizStatus.REQUEST_VERIFICATION_FLAG_BIT);
        }

        if ("1".equals(checkFlag)) {
            identityCheck(request, response, checkFlag);
        }else {
            messagePush(request, response, checkFlag);
        }

    }

    public static void main(String[] args) {
        StringBuilder builder = new StringBuilder();


//        boolean passed = IcbcSignature.verify(signStr, "RSA", mchApp.getAppPublicKey(), "UTF-8", icbcSign);
    }
}
